package no.evalanche.statsgraph;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;

public class ResultsGraphics extends View {

	private final int XREPEAT = 150;
	private final int HEIGHT_REDUCTION = 100;
	private int STAPLE_WIDTH = 40;

	private JSONObject json;
	private int staplePerioodCount = 0;
	private int highestStaple;

	public ResultsGraphics(Context context, JSONObject j) {
		super(context);
		json = j;
	}

	private void drawOperations(Canvas c, StaplePeriod s) {
		c.drawRect(s.clickedR, s.clickedP);
		c.drawRect(s.solvedR,  s.solvedP);
		s.solvedP.setTextSize(30);
		c.drawText(s.label, s.clickedR.left, HEIGHT_REDUCTION + 7, s.solvedP);
	}

	private StaplePeriod staple(String s) throws JSONException {
		return new StaplePeriod(json, s, this);
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		try {
			highestStaple = json.getJSONObject("best").getInt("clicked");
			drawOperations(canvas, staple("you"));
			drawOperations(canvas, staple("they"));
			drawOperations(canvas, staple("best"));
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	/* ******************************************** */

	private final class StaplePeriod {
		private final int XR = -10;
		private RectF clickedR;
		private RectF solvedR;
		private Paint clickedP;
		private Paint solvedP;
		private String label = null;

		StaplePeriod(JSONObject j, String s, View v) throws JSONException {
			label = s;
			JSONObject json = j.getJSONObject(s);
			float height = v.getHeight() - HEIGHT_REDUCTION;
			float clicked = 0;
			float solved = 0;
			clicked = json.getInt("clicked");
			solved = json.getInt("solved");
			staplePerioodCount++;
			float x = staplePerioodCount * XREPEAT;
			clickedR = new RectF(x, v.getBottom()
					- (clicked / highestStaple * height), x + STAPLE_WIDTH,
					v.getBottom());
			x += (STAPLE_WIDTH + XR);
			solvedR = new RectF(x, v.getBottom()
					- (solved / highestStaple * height), x + STAPLE_WIDTH,
					v.getBottom());
			clickedP = new Paint();
			solvedP = new Paint();
			clickedP.setColor(Color.GRAY);
			solvedP.setColor(Color.YELLOW);
		}
	}

}
